package com.oceansoft.mobile.biz.api.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.common.util.StringUtils;
import com.oceansoft.mobile.weixin.util.RequestUtils;
import com.oceansoft.mobile.weixin.util.WeixinUtil;

/**
 * Created by zhuya on 2016/3/3.
 */
@Controller
@RequestMapping("api/sgcltxz")
public class ApiSgcltxzController {
    //基本信息模板
    public static String Jbxxmb =Constant.host5+"api/SGCLTXZ/GetJBXX?userid=";
    //通过guid获取基本信息
    public static String JbxxmbDetail =Constant.host5+"api/SGCLTXZ/GetJBXXByGuid?guid=";
    //获取所有车辆
    public static String Clmb =Constant.host5+ "api/SGCLTXZ/GetCLMB?userid=";
    //获取车辆模板
    public static String ClmbDetail =Constant.host5+"api/SGCLTXZ/GetCLMBbyguid?guid =";
    //施工车辆申请接口
    public static String SgcltxzReport =Constant.host5+"api/SGCLTXZSQ/setSgcltxzReport";
    //申报数据推送接口
    public static String Shenbao =Constant.host5+"api/Product/Shenbao";
    //施工车辆申请接口
    public static String SaveProjectMa =Constant.host5+"/api/Product/SaveProjectMa";
    //车辆行驶证
    public static String cltxz ="302b5540-989c-485e-93dd-6d8f332ed0c0";
    //工地工程计划
    public static String gdgcjh ="1f702b85-56bc-406b-8ec1-7491db873bec";
    //证明申请理由的其他材料
    public static String qtcl ="ca5ff58a-685c-49ea-9397-8a2eb4cb49b6";
    //施工车辆通行证code
    public static String sgcltxz_code ="faaffd48-65d0-41c1-9192-d946bd92ee34";
    //获取事项详情
    public static String getcase =Constant.host5+"/api/getcase/GetDetail";



    /*
    * 加载施工车辆
    *
            * @param model
    * @return
            * @throws Exception
    */
    @RequestMapping(value = "item_details")
    public String sgcltxz1(HttpServletRequest request,Model model){
    	String source = (String) request.getSession().getAttribute("source");
	       if (StringUtils.isNotBlank(source)) {
	       	model.addAttribute("source", source);
	       }
        return "weixin/matters/item_details";
    }

    /*
    * 跳转施工车辆信息
    *
            * @param model
    * @return
            * @throws Exception
    */
    @RequestMapping(value = "sgcltxz2")
    public String sgcltxz2(HttpSession session,HttpServletRequest request,
                             Model model)throws IllegalArgumentException, IOException {
        Map<String, String> param = new HashMap<String, String>();
        boolean b = WeixinUtil.checkIsLoginUser(request);
        String source = (String) request.getSession().getAttribute("source");
	       if (StringUtils.isNotBlank(source)) {
	       	model.addAttribute("source", source);
	       }
//        b=true;
        if(!b){
            model.addAttribute("openId",(String)session.getAttribute("openId"));
            model.addAttribute("gotoPage","/api/sgcltxz/sgcltxz2");
            return "weixin/login/login";
        }else{
            Member member = (Member)session.getAttribute(Constant.SESSION_USER);
            session.removeAttribute(Constant.SESSION_SGCLTXZSQ);
            session.removeAttribute(Constant.SESSION_SGCL_FJ);
            session.removeAttribute(Constant.SESSION_SGCL_TY);
            model.addAttribute("userId", member.getGuid());
            return "weixin/matters/sgcltxz2";
        }
    }

    /*
   * 跳转施工车辆
   *
           * @param model
   * @return
           * @throws Exception
   */
    @ResponseBody
    @RequestMapping(value = "sgcltxz3")
    public Result sgcltxz4(HttpSession session,HttpServletRequest request,
                             Model model)throws IllegalArgumentException, IOException {
        Map<String, String> param = new HashMap<String, String>();
        param = (Map<String, String>)session.getAttribute(Constant.SESSION_SGCLTXZSQ);
        param.put("Glguid",request.getParameter("Glguid"));
        String url =SgcltxzReport+"?guid="+param.get("jbxxmb")+"&beginTime="+param.get("BeginTime")+"&endTime="+param.get("EndTime")+"&glguid="+param.get("Glguid")+"&xlguid="+param.get("Sglxmb");
        Result result = JSONObject.parseObject(HttpClientUtil.doGet(url), Result.class);
        String guid="";
        if(result.isSucc()){
            guid= (String)result.getData();
        }
        //请空map，将通用接口信息存session
        param.clear();
        param.put("projectGuid",guid);
        session.setAttribute(Constant.SESSION_SGCL_TY,param);
        return result;
    }



    /*
   * 跳转施工车辆
   *
           * @param model
   * @return
           * @throws Exception
   */
    @RequestMapping(value = "sgcltxz1")
    public void sgcltxz3(HttpSession session,HttpServletRequest request,
                             Model model)throws IllegalArgumentException, IOException {
        Member member = (Member)session.getAttribute(Constant.SESSION_USER);
        Map<String, String> param = new HashMap<String, String>();
        param = RequestUtils.buildParamsByNamesFromRequest(request);
        session.removeAttribute(Constant.SESSION_SGCLTXZSQ);
        session.setAttribute(Constant.SESSION_SGCLTXZSQ,param);
    }

    /**
     * 基本信息模板
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "Jbxxmb", method = GET)
    public Result Jbxxmb(@RequestParam(value = "guid", required = true) String guid) throws IllegalArgumentException, IOException {
        //测试用于显示模板
        if("00000".equals(guid)){
            guid="5146515f-f9ff-4d23-9ec4-b395a2243fd1";
        }
        String resp = HttpClientUtil.doGet(Jbxxmb + guid);
        Result result = new Result();
        if (StringUtils.isNotBlank(resp)) {
            JSONObject respData = JSON.parseObject(resp);
            boolean succ = "true".equalsIgnoreCase(respData.getString("succ"));
            if (succ) {
                JSONObject data = new JSONObject();
                data.put("list", respData.getJSONArray("data"));
                final JSONArray data1 = respData.getJSONArray("data");
//                model.addAttribute("data",data1);
                result.setData(data1);
            }
        }
        return result;
    }
    /**
     * 基本信息模板明细
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "JbxxmbDetail", method = GET)
    public Result JbxxmbDetail(@RequestParam(value = "guid", required = true) String guid) throws IllegalArgumentException, IOException {
        String resp = HttpClientUtil.doGet(JbxxmbDetail + guid);
        Result result = new Result();
        if (StringUtils.isNotBlank(resp)) {
            JSONObject respData = JSON.parseObject(resp);
            boolean succ = "true".equalsIgnoreCase(respData.getString("succ"));
            if (succ) {
//                JSONObject data = JSON.parseObject(respData.get("data").toString());
//                model.addAttribute("data",respData.getJSONArray("data"));
                result.setData(respData.getJSONArray("data"));
            }

        }
        return result;
    }
    /**
     * 车辆信息模板
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "Clmb", method = GET)
    public Result Clmb(@RequestParam(value = "guid", required = true) String guid) throws IllegalArgumentException, IOException {
        String resp = HttpClientUtil.doGet(Clmb + guid);
        Result result = new Result();
        if (StringUtils.isNotBlank(resp)) {
            JSONObject respData = JSON.parseObject(resp);
            boolean succ = "true".equalsIgnoreCase(respData.getString("succ"));
            if (succ) {
                JSONObject data = new JSONObject();
                data.put("list", respData.getJSONArray("data"));
                final JSONArray data1 = respData.getJSONArray("data");
                result.setData(data1);
//                model.addAttribute("data",data1);
            }
        }
        return result;
    }
    /**
     * 申报
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "report", method = GET)
    public Result submitsgcltxz(HttpSession session,HttpServletRequest request) throws IllegalArgumentException, IOException {
        String url = Constant.host + "/api/matters/shenBao";
        Map<String, String> param = new HashMap<String, String>();
        param = (Map<String, String>) session.getAttribute(Constant.SESSION_SGCL_TY);
        //附件Id
        Map<String ,Result> m = (Map<String , Result>)session.getAttribute("sgcl_fj");
        session.removeAttribute(Constant.SESSION_SGCLTXZSQ);
        session.removeAttribute("sgcl_fj");
        session.removeAttribute(Constant.SESSION_SGCL_TY);
        Member member = (Member)session.getAttribute(Constant.SESSION_USER);
        if(null==m||m.isEmpty())
        {
            return new Result(false);
        }
        String fjguid = "";
        String caseMatGuid = "";
        //循环读取附件
        Set<String> fjkeys = m.keySet();
        for (String key : fjkeys) {
           Result r = m.get(key);
            fjguid += ((JSONObject)r.getData()).get("prjMatGuid")+";";
            caseMatGuid+= ((JSONObject)r.getData()).get("caseMatGuid")+";";
        }
        param.put("fjguid", fjguid);
        param.put("declareCaseGuid",sgcltxz_code);
        param.put("caseMatGuid", caseMatGuid);
        //附加用户信息
        RequestUtils.putUser(request, param);
        Result rst = JSONObject.parseObject(HttpClientUtil.doPost(url, param, "utf-8"), Result.class);
        return rst;
    }

   
    /**
     *施工车辆图片上传2
     * @param base64
     * @return
     */
    @ResponseBody 
    @RequestMapping(value="uploadMsg",method= RequestMethod.POST)
    public Result uploadMsg(HttpServletRequest request){
        //type字段用于识别前台传过来的不同图片
    	String type=request.getParameter("type");
		String seesionname = request.getParameter("imgname");
		String base64 = request.getParameter("base64");
		String name=request.getParameter("name");
        String caseMatGuid = "";
        if("1".equals(type)){
            caseMatGuid=cltxz;//,qtcl
        }else if("2".equals(type)){
            caseMatGuid=gdgcjh;//gdgcjh,
        }else if("3".equals(type)){
            caseMatGuid=qtcl;//gdgcjh,qtcl
        }
        Result result =  RequestUtils.saveFj(request, base64, caseMatGuid, true);
//        Result result = uploadFJ(type, request, "pzctrl", caseMatGuid);
        Map<String,Result> m = (Map<String , Result>)request.getSession().getAttribute(name);
        request.getSession().removeAttribute(name);
        if(null==m)
        {
            m = new HashMap<String, Result>();
        }
        m.put(seesionname, result);
        request.getSession().setAttribute(name, m);
        return result;
    }

    /**
     * 车辆信息模板
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "getDetail", method = GET)
    public Result getDetail(HttpServletRequest request,Model model) throws IllegalArgumentException, IOException {
        Map<String, String> param = new HashMap<String, String>();
        String type=request.getParameter("type");
        if("0".equals(type)){
            param.put("refid","687a63ec-7e65-41e3-b90a-7febc72dc9a4");//货车
        }else{
            param.put("refid","faaffd48-65d0-41c1-9192-d946bd92ee34");//施工
        }
        param.put("orgId","F1DBDF352FC94EA28A020559048718A7");
        String resp = HttpClientUtil.doPost(getcase,param,"utf-8");
        Result result = new Result();
        if (StringUtils.isNotBlank(resp)) {
            JSONObject respData = JSON.parseObject(resp);
            boolean succ = "true".equalsIgnoreCase(respData.getString("succ"));
            if (succ) {
                JSONObject data = new JSONObject();
                data =JSONObject.parseObject(respData.get("data").toString());
                data.put("list", data.get("baseInfo"));
               // final JSONArray data1 = respData.getJSONArray("data");
                result.setData(data.get("baseInfo"));
            }
        }
        return result;
    }
}
